package wili.sql;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 *
 */
public class Sql9 {
	public static String getColumn(ResultSet rs, int index) {
		ResultSetMetaData meta = null;
		try {
			meta = rs.getMetaData();
			return meta.getColumnName(index);
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
	}

	public static String getColumn(ResultSet rs, String... cols) {
		ResultSetMetaData meta = null;
		try {
			meta = rs.getMetaData();
			int num = meta.getColumnCount();
			for (int i = 0; i < num; i++) {
				String nam = meta.getColumnName(i + 1).toLowerCase();
				for (int k = 0; k < cols.length; k++) {
					if (cols[k].equalsIgnoreCase(nam))
						return cols[k];
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static List<String> columnNameListOf(ResultSet rs, boolean sortByName) {
		try {
			ResultSetMetaData meta = rs.getMetaData();
			int num = meta.getColumnCount();
			List<String> cc = new ArrayList<>(num);
			for (int i = 0; i < num; i++) {
				cc.add(meta.getColumnName(i + 1));
			}
			if (sortByName) {
				Collections.sort(cc);
			}
			return cc;
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
	}
}
